package top.broncho.gank.ui.activity

import android.app.Application
import androidx.lifecycle.MutableLiveData
import top.broncho.gank.api.ApiService
import top.broncho.gank.bean.HotSearchBean
import top.broncho.gank.db.AppDataBase
import top.broncho.gank.db.HistoryEntity
import top.broncho.gank.http.exception.ErrorStatus
import retrofit2.Retrofit
import retrofit2.create
import top.broncho.mvvm.base.BaseViewModel
import javax.inject.Inject

class SearchViewModel @Inject constructor(
    app: Application,
    private val db: AppDataBase,
    private val retrofit: Retrofit
) :
    BaseViewModel(app) {
    private val api by lazy { retrofit.create<ApiService>() }
    val history = MutableLiveData<Result<MutableList<HistoryEntity>>>()
    val hotSearch = MutableLiveData<Result<MutableList<HotSearchBean>>>()

    fun getHotSearchData() = launchOnlyResult(
        block = {
            api.getHotSearchData()
        },
        success = {
            hotSearch.postValue(Result.success(it))
        },
        error = {
            hotSearch.postValue(Result.failure(it))
        }
    )

    fun deleteById(id: Long) = launchUI {
        db.historyDao().deleteHistory(id)
    }

    fun clearAllHistory() = launchUI {
        db.historyDao().deleteAll()
    }

    fun saveSearchKey(key: String) = launchUI {
        val bean = db.historyDao().getHistory(key.trim())
        if (bean != null) {
            db.historyDao().delete(bean)
        }
        db.historyDao().insert(HistoryEntity(keyWord = key.trim()))
    }

    fun queryHistory() = launchUI {
        val historyBeans = db.historyDao().getHistories()
        historyBeans.reversed()
        history.postValue(Result.success(historyBeans))
    }
}